package com.example.mqtt.config;

/**
 * @author qwert
 * @version 1.0.0
 * @create 2025/4/21 20:12
 **/
import com.hivemq.client.mqtt.MqttClient;
import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Configuration
public class MqttConfig {

    private static final String BROKER_HOST = "47.97.31.111";
    private static final int BROKER_PORT = 1883;
    private static final String CLIENT_ID = "emqx_MDg2OD";
    private static final String USER_NAME = "user";
    private static final String USER_PASSWORD = "public";

    @Bean
    public Mqtt5AsyncClient mqttClient() {
        String uniqueClientId = CLIENT_ID + "-" + UUID.randomUUID().toString().substring(0, 6);

        Mqtt5AsyncClient client = MqttClient.builder()
                .useMqttVersion5()
                .identifier(uniqueClientId)
                .serverHost(BROKER_HOST)
                .serverPort(BROKER_PORT)
                .simpleAuth()
                .username(USER_NAME)
                .password(USER_PASSWORD.getBytes())
                .applySimpleAuth()
                .automaticReconnect()
                .initialDelay(1, TimeUnit.SECONDS)
                .maxDelay(30, TimeUnit.SECONDS)
                .applyAutomaticReconnect()
                .buildAsync();
        client.connectWith()
                .keepAlive(30) // 保活时间（秒）
                .send()
                .whenComplete((connAck, throwable) -> {
                    if (throwable != null) {
                        System.err.println("连接失败: " + throwable.getMessage());
                    } else {
                        System.out.println("成功连接到 Broker: " + BROKER_HOST + ":" + BROKER_PORT);
                    }
                });

        return client;

    }
}
